<template>
  <!-- 巡检路线表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '850px' : '850px'"
      draggable
      style="min-height: 600px; position: relative"
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
        v-show="!props.isReadonly"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="路线编号"
                prop="routeCode"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.routeCode"
                  placeholder="请输入路线编号"
                  clearable
                />
                <span v-else>{{ formData.routeCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="路线名称"
                prop="routeName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.routeName"
                  placeholder="请输入路线名称"
                  clearable
                />
                <span v-else>{{ formData.routeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">路线位置数据</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>
        <div>
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
            class="formTable3"
            max-height="240px"
            overflow-y="auto"
          >
            <el-table-column
              label="排序"
              props="sort"
              min-width="50"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.sort'"
                  :rules="rules.sonsort"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.sort"
                    placeholder="请输入排序"
                    clearable
                  />
                  <span v-else>{{ row.sort }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              label="位置名称"
              props="locationName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.locationName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        title=""
        :column="2"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">路线编号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.routeCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">路线名称</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.routeName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-if="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-else type="info">停用</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <el-table
        :data="formData.details"
        style="width: 100%; margin-top: 20px"
        :key="Math.random"
        v-show="props.isReadonly"
        max-height="240px"
        overflow-y="auto"
        border
        class="formTable4"
      >
        <el-table-column
          label="排序"
          props="sort"
          min-width="50"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.sort ? row.sort : $index }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="位置名称"
          props="locationName"
          min-width="150"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.locationName }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div
          class="dialog-footer"
          style="position: absolute; bottom: 30px; right: 20px"
        >
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <common-location-select
      :visible="selectLocationDialog.visible"
      :LocationList="LocationList"
      @change-visible="changeLocationVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "COMMONINSPECTIONROUTEEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  assetKind: props.assetKind,
  routeCode: "",
  routeName: "",
  deleted: "",
  enabled: 1,
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    // {
    //   id: "",
    //   version: "",
    //   routeId: "",
    //   sort: "",
    //   locationId: "",
    //   locationName: "",
    //   organizationId: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  assetKind: [],
  routeCode: [
    { required: true, message: "请输入路线编号", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  routeName: [
    { required: true, message: "请输入路线名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonsort: [
    {
      required: true,
      message: "请输入序号",
      trigger: "blur",
      pattern: /^([1-9]{1,3}|100)$/,
    },
  ],
  sonlocationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonlocationName: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  routeId: "",
  sort: "",
  locationId: "",
  locationName: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  selectLocationDialog.value.visible = true;
  if (formData.details.length > 0) {
    getLocationList();
  }
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      } else {
        formData.assetKind = props.assetKind;
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.id = "";
  formData.version = "";
  formData.assetKind = props.assetKind;
  formData.routeCode = "";
  formData.routeName = "";
  formData.deleted = "";
  formData.enabled = 1;
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 巡检路线保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (formData.details.length <= 0) {
        ElMessage.error("请选择至少一项资产位置");
        return;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eamInspectionRoute/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eamInspectionRoute/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 资产位置
//资产位置显隐
const selectLocationDialog: any = ref({
  visible: false,
});
const changeLocationVisible = (val: boolean, data: any) => {
  if (data) {
    console.log(data);
    formData.details = [];
    data.forEach((item, index) => {
      formData.details.push({
        locationId: item.id,
        locationCode: item.locationCode,
        locationName: item.locationName,
        sort: index + 1,
      });
    });
  }
  selectLocationDialog.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const LocationList = ref([]);

const getLocationList = () => {
  LocationList.value = [];
  formData.details.forEach((item) => {
    if (item.locationId) {
      LocationList.value.push({
        id: item.locationId,
        locationCode: item.locationCode,
        locationName: item.locationName,
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.formTable3 {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.formTable3 .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.formTable3 .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.formTable3) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }
  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 130px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
